//获取随机字符串
function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

//null转空字符串
function NullToBlank(value){
    if(value==undefined) return "";
    else return value;
}


//检查手机号
function checkMobile(mobile){
    var reg = /^0?1[35789]{1}[0-9]\d{8}$/;
    return reg.test(mobile) ? true : false;
}

//求和
function getSum(data) {
    if(data.length==0) return 0.0;
    return data.reduce(function (a,b) {
        return a+b;
    })
}
/**
 * 获取下一个编码 000001，000001000006，6
 * 得到结果 000001000007
 */
function getNextCode(prefix,maxCode,length){
    if(maxCode==null){
        var str="";
        for(var i=0;i<length-1;i++){
            str+="0";
        }
        return prefix+str+1;
    }else{
        var str="";
        var sno = parseInt(maxCode.substring(prefix.length))+1;
        for(var i=0;i<length-sno.toString().length;i++){
            str+="0";
        }
        return prefix+str+sno;
    }

}

//根据url，参数data初始化table中的数据
function initTable(pageUrl,searchUrl,searchDiv,table,pageSize,paging,editIcon,editTitle,deleteIcon,deleteTitle){
    editIcon=editIcon||'fa fa-edit';
    deleteIcon=deleteIcon||'fa fa-trash-o';
    editTitle=editTitle||'编辑';
    deleteTitle=deleteTitle||'删除';
    var object=new Object();
    var getDataBySearchId=function(){
        var param={};
        $(searchDiv).find("input[name],select[name]").each(function(index,value){
            param[$(this).attr("name")]=$(this).val();
        });
        param['size']=pageSize.val()||pageSize.find(".page_active").text();
        return param;
    }
    var changeFunction=function(){
        $(searchDiv).find("input[name],select[name]").change(function(){
            $(paging).find("a.active").removeClass("active");
            search();
        })
        $(searchDiv).find("[data-btn-type='search']").click(function(){
            $(paging).find("a.active").removeClass("active");
            search();
        })
        pageSize.change(function(){
            $(paging).find("a.active").removeClass("active");
            search();
        })
    }

    var selectAll=function () {
        if(table.find("thead tr th input:checkbox").length>0){
            table.find("thead tr th input:checkbox").change(function () {
                if($(this).prop("checked")==true){
                    table.find("tbody input:checkbox").prop("checked",true);
                }else{
                    table.find("tbody input:checkbox").prop("checked",false);
                }
            })
        }
    }

    var search=function(){
        var param=getDataBySearchId();
        AsyncGet(pageUrl,param,function(totalPage){
            $(table).find("tbody").empty();
            startPage(paging,totalPage,function(page){
                if(totalPage==0) return;
                param['page']=page-1;
                AsyncGet(searchUrl,param,function(value){
                    $(table).find("tbody").empty();
                    for(var i=0;i<value.length;i++){
                        var tr="<tr>";
                        $(table).find("thead th").each(function(){
                            if($(this).find("input:checkbox").length>0){
                                tr+="<td style='text-align: center;'><input type='checkbox'></td>";
                            }else if($.trim($(this).attr("name"))==""){
                                tr+="<td style='text-align: center;'>" +
                                    "<a class='"+editIcon+"' title='"+editTitle+"' style='cursor:pointer;margin: 0 10%;'></a>"+
                                    "<a class='"+deleteIcon+"' title='"+deleteTitle+"' style='cursor:pointer;margin: 0 10%;'></a>"+
                                    "</td>";
                            }else if($(this).is(":hidden")){
                                tr+="<td style='display:none;'>"+NullToBlank(value[i][$(this).attr("name")])+"</td>";
                            }else{
                                if($(this).attr("format")!=null){
                                    var date=new Date(value[i][$(this).attr("name")]*1000);
                                    tr+="<td style='text-align: center;'>"+date.Format($(this).attr("format"))+"</td>";
                                }else{
                                    tr+="<td style='text-align: center;'>"+NullToBlank(value[i][$(this).attr("name")])+"</td>";
                                }
                            }
                        })
                        tr+="</tr>";
                        $(table).find("tbody").append(tr);
                    }

                })
            },5, modals.error);
        })
    }
    search();
    changeFunction();
    selectAll();
    object.search=search;
    return object;
}

/*
*param{
*
*  htmlUrl          ,实体的url
*  addHtmlUrl          ,实体的url
*  updateHtmlUrl          ,实体的url
*  updateEntityUrl  ,修改实体的url
*  updateBeforeCallback  ,修改实体之前的回调,
*  addEntityUrl     ,添加实体的url
*  addBeforeCallback  ,添加实体之前的回调,
*  deleteEntityUrl  ,删除的url
*  deleteId         ,删除的id参数
*  getEntityUrl     ,获取实体的url
*  getId            ,获取实体的id参数
*  getEntityBefore  ,获取实体之前
*  initFormDataCallback, 填充表单后的回调
*  initFormDataBeforeCallback , 填充表单前的回调
*  editTitle        ,编辑title
*  table            ,表格
*  addButton        ,添加按钮
*  addButtonCallback,添加界面显示之后的回调
*  addTitle         ,添加title
* }
* callback          ,操作成功的回调函数
**/
function EditEntity(param,callback){
    var winId=randomString();
    var clickId;
    var type="update";
    modals.openWin({
        winId:winId,
        url:param.htmlUrl?param.htmlUrl:param.updateHtmlUrl?param.updateHtmlUrl:param.addHtmlUrl,
        show:false,
    })
    var modal=$("#"+winId);

    if(param.deleteEntityUrl!=null){
        param.table.on("click","tbody td a:last-child",function(){
            clickId=$(this).parents("tr").find("td:first").text();
            modals.confirm("确定删除吗?",function () {
                AsyncDelete(param.deleteEntityUrl+"/"+clickId,null,function(value){
                    modals.correct("删除成功",callback);
                })
            })
        })
    }else{
        param.table.find("tbody td a:last-child").hide();
    }

    if(param.getEntityUrl!=null){
        param.table.on("click","tbody td a:first-child",function(){
            clickId=$(this).parents("tr").find("td:first").text();
            if(param.addHtmlUrl&&param.updateHtmlUrl){
                modal.find('.modal-body').load(param.updateHtmlUrl,function () {
                    modals.showWin(modal.attr("id"));
                    if(param.updateEntityUrl) type="update";
                    modal.find('.modal-title').text(param.editTitle);
                    modal.find('[onlyread]').prop("disabled",true);
                    modal.find('[updateonlyread]').prop("disabled",true);
                    modal.find('[addonlyread]').prop("disabled",false);
                    if(param.getEntityBefore) param.getEntityBefore();
                    initFormData(param.getEntityUrl+"/"+clickId,null,modal.find(".modal-body form"),
                        param.initFormDataCallback,param.initFormDataBeforeCallback);
                });
            }else{
                modals.showWin(modal.attr("id"));
                if(param.updateEntityUrl) type="update";
                modal.find('.modal-title').text(param.editTitle);
                modal.find('[onlyread]').prop("disabled",true);
                modal.find('[updateonlyread]').prop("disabled",true);
                modal.find('[addonlyread]').prop("disabled",false);
                if(param.getEntityBefore) param.getEntityBefore();
                initFormData(param.getEntityUrl+"/"+clickId,null,modal.find(".modal-body form"),
                    param.initFormDataCallback,param.initFormDataBeforeCallback);
            }
        })
    }else{
        param.table.find("tbody td a:first-child").hide();
    }

    if(param.addButton!=null){
        param.addButton.click(function(){
            if(param.addHtmlUrl){
                modal.find('.modal-body').load(param.addHtmlUrl,function () {
                    modals.showWin(modal.attr("id"));
                    if(param.addEntityUrl) type="add";
                    modal.find('.modal-title').text(param.addTitle);
                    modal.find('[onlyread]').prop("disabled",true);
                    modal.find('[updateonlyread]').prop("disabled",false);
                    modal.find('[addonlyread]').prop("disabled",true);
                    clearFormData(modal.find(".modal-body form"));
                    if(param.addButtonCallback) param.addButtonCallback();
                });
            }else {
                modals.showWin(modal.attr("id"));
                if(param.addEntityUrl) type="add";
                modal.find('.modal-title').text(param.addTitle);
                modal.find('[onlyread]').prop("disabled",true);
                modal.find('[updateonlyread]').prop("disabled",false);
                modal.find('[addonlyread]').prop("disabled",true);
                clearFormData(modal.find(".modal-body form"));
                if(param.addButtonCallback) param.addButtonCallback();
            }
        })
    }

    if(param.updateEntityUrl||param.addEntityUrl){
        modal.find(".modal-footer button:last").show().unbind("click").click(function(){
            var form=getFormData(modal.find(".modal-body form"));
            console.log(clickId);
            form=$.extend({id:clickId},form);
            if(type=="add"){
                if(param.addBeforeCallback) form=param.updateBeforeCallback(form);
                AsyncPost(param.addEntityUrl,form,function(value){
                    modals.hideWin(modal.attr("id"));
                    modals.info("操作成功",callback);
                })
            }
            if(type=="update"){
                if(param.updateBeforeCallback) form=param.updateBeforeCallback(form);
                AsyncPut(param.updateEntityUrl,form,function(value){
                    modals.hideWin(modal.attr("id"));
                    modals.info("操作成功",callback);
                })
            }
        })
    }else{
        modal.find(".modal-footer button:last").hide();
    }
    return winId;
}

